import re

from rest_framework import serializers

from users.models import User


class UserSerializer(serializers.ModelSerializer):
    """
    用序列化
    """

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'password')
        extra_kwargs = {  # 自定义显示
            'password': {
                'write_only': True,
                'max_length': 20,
                'min_length': 8,
            },
            'username': {
                'max_length': 20,
                'min_length': 5,
            }
        }

    def validated_mobile(self, value):
        """
        单一字段验证
        :param value: 手机号码
        :return:  手机号码
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机格式不正确')
        return value

    def create(self, validated_data):
        # **validated_data 拆包操作
        return User.objects.create(**validated_data)
